"""
此模块用于获取所有股票代码，调用分析函数进行诊断，
并显示操作建议为买入（operation 为 1）的股票信息。
"""
from . import custommodule, manager
import sqlite3
import pandas as pd


def recommend_stocks(stock_codes:list=None):
    """
    获取所有股票代码，调用 analyze_watchlist 进行诊断，
    显示 operation 为 1 的股票代码及名称。
    """
    if stock_codes is None:stock_codes = [code for code, _ in custommodule.get_all_stocks_info()]
    analysis_result = manager.analyze_watchlist(stock_codes)

    if not analysis_result.empty:
        buy_stocks = analysis_result.loc[analysis_result['operation'] == 1, ['stock_code', 'stock_name']]
        if buy_stocks.empty:print("没有操作建议为买入的股票。")
    else:
        print("没有有效的分析结果。")

    try:
        with sqlite3.connect('db_file.db') as conn:
            # 从 Strategy 类获取策略名称对应的列名
            strategy_name = custommodule.Strategy.strategys()[1]
            query = f"SELECT stock_code, {strategy_name} FROM backtest"# WHERE {strategy_name} > 0"
            result = pd.read_sql(query, conn)

        # 合并 buy_stocks 和 result 中 stock_code 值相同的数据
        merged_data = pd.merge(buy_stocks, result, on='stock_code', how='inner')
        # 按策略结果降序排序
        merged_data = merged_data.sort_values(by=strategy_name, ascending=False)
        # 剔除stock_code开头为688的股票
        merged_data = merged_data[~merged_data['stock_code'].str.startswith('688')]
        return merged_data
    except Exception as e:
        print(f"查询数据库出错: {str(e)}")
        return None


def menu():
    print("正在计算推荐买入的股票...")
    stock_codes = recommend_stocks()
    print(f"今日推荐买入的股票如下：\n{stock_codes}")
    try:
        # 获取推荐买入的股票代码列表，在stock_info表中将is_watchlist设为2
        stock_codes = stock_codes['stock_code']
        with sqlite3.connect('db_file.db') as conn:
            cursor = conn.cursor()
            cursor.execute("UPDATE stock_info SET is_watchlist = NULL WHERE is_watchlist = 2")
            for code in stock_codes:
                cursor.execute("UPDATE stock_info SET is_watchlist = 2 WHERE stock_code LIKE ? || '%'", (code,))
            conn.commit()
        print("推荐股数据已更新！")
    except Exception as e:
        print(f"计算推荐股出错: {str(e)}")
